iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 1
0
自我挑戰組

我所知道的計算機 2019 What I know about computers系列 第 3

第三天(?)來點 JavaScript! some JavaScripts!

  • 分享至 

  • xImage
  •  

For English version, please scroll down.

今天我們就 JavaScript 及其運行環境:瀏覽器,如何操作 DOM, 事件, 函式庫 D3, 最後畫一個小地圖作結。

以下的範例可以在我們每次在頁面上點了滑鼠之後,
更新畫面上顯示的點擊次數

const reading = document.querySelector(`#count`)
let count = 0
document.addEventListener(`click`, (event)=>{
    count = count + 1
    reading.innerHTML = `Count: ${count}`
})

https://codepen.io/owlfox/pen/bGbyZjV
程式語言裡常出現 "物件/Object" 的概念,大概可以想成把相關連的資料、程式分類擺好以利使用。

  • document 是JS瀏覽器運行時可存取的全域物件,它就對應了我們整份 HTML 文件被瀏覽器讀取後的樹狀資料結構,
  • 這裡我們拿了 document 執行 querySelector 函數, 並要求他去搜尋 id 爲 count 的 html element,並把找到的結果存在 reading 裡
  • 我們可以讓瀏覽器在我們做出按下鍵盤、點擊滑鼠等各種動作的時候做出回應。這裡第3行我們就是讓整個網頁在被點的時候紀錄被點的次數並輸出結果到其中一個 html element.

一點小歷史

JavaScript(後簡稱為JS)是在 1995 年,那個 IE, Chrome, Firefox 還不知道在那裡的年代,由一位 Brendan Eich 先生爲 Netscape 這家公司的網路瀏覽器開發的程式語言。

這個“語言”讓我們可以交代瀏覽器在打開了一個超連接,讀取網頁的 html 檔案、把網頁畫出來之後,可以依跟使用者的輸入做出一些互動。

JS 後來被許多瀏覽器廠家採用,European Computer Manufacturers Association (ECMA) 這個組織後來主導了 JS 語言的語法,讓各瀏覽器可以執行相同的程式,得到相同的結果。而這個協定有各種不同版本,我們也叫 JavaScript EcmaScript,所以你會看到以 ES2015/ES6 來稱呼的 JS 語言版本。如果想知道一些新的 JS, CSS 語法在各瀏覽器上是不是都有實作,可以參考 caniuse 網頁上的資訊。

DOM

DOM 就是 Document Object Model ,基本上就是個每個英文字都知道意思,但是拼起來就不知道是什麼的術語。這裡我是想成各家瀏覽器在收到 html 文件之後都會以自己的邏輯把資料存好供 JS 跟 CSS 存取。而 W3C 制定的規範就是要求大家都把資料依照類似的結構整理好,讓不同的程式碼得到相同的執行成果。 我們在上面的例子裡面就是透過 JS 對 DOM 進行一個操作的動作。

Chrome 開發者工具

寫程式時常會有不如預期、需要除錯的時候。我們的瀏覽器除了可以用來看,還可以用來幫我們找錯誤。當你在網頁上點右鍵->查看元素的之後,瀏覽器會開出一個小視窗顯示 html 的原始碼,其對應的 CSS 風格、你也可以 source 分頁在 JS 裡面加入中斷點,在 console 裡面直接寫 JS 原始碼,觀察錯誤訊息、程式運行狀態,以及在網路分頁裡面看看這個網頁下載了哪些檔案,跟背地裡送/拿了哪些資料。
底下出現的範例基本上你都可以直接貼到 console 裡面去看結果,

一些 ES6 的語法介紹

因為系列文章有用到,這裡稍微介紹一下 ES6 的語法。

  • const,之後不會再改的常數
  • let ,其他變數
  • var (可以的話避免使用,可能會宣告成全域變數,造成混淆。)
  • 箭頭函式(()=>()) 更簡短的函式語法,適合用在 map, filter 函數的參數裡。
  • module 當專案規模變大或是使用外部模組的時候需要用到 export/import 語法
  • classes 其他物件導向程式語言有的類別在 ES6 裡也開始得到支援。
    類別 / Class 就像是蓋房子的藍圖,我們可以把相關資料跟存取資料的程式碼整理在一起。
class Animal {
 constructor(name) {
     this.name = name
 }
 printName() {
     console.log(this.name)
 }
}

class Dog extends Animal {
  bark() {
  console.log(`${this.name}: Bow!`)
  }
}

let beddy = new Dog("beddy")
beddy.bark()
//beddy: Bow!
  • ... spread/Rest operator
    我們可以用 ... 把 一個陣列展開
let a = [1,2,3]
let b = [...a, 4] //[1,2,3,4]

或是把函數的參數組織成一個陣列

function f(...args){
    return args.filter(e=>e===1)
}
f(1,2,3,4) //return [1]
  • destructuring 把陣列/物件裡面需要的元素“提"出來
let a, b = 1, 2
[a,b] = [b,a]
let a = {name:"beddy", age: -1}
let {name, age} = a 
  • Reference / Primitive types
    JS 有六種原始/Primitive資料型態 string、number、boolean、null、undefined、symbol,還有其他的各種物件。當我們在操作/指定變數內容的時候,只有 Primitive 會在記憶體中實際複製一份,而大多情況我們只是給個物件的Reference。
let a = 2
let b = a
b = 3
console.log(a,b) 
//2,3 a real copy

let c = [1]
let d = c
d.push(2) 
console.log(c,d) 
//[1,2] [1,2] just a reference, 
//you are playing the same object
  • map 這裡 JS 的 map 函數是將陣列裡的每個元素都經過"映射",跟我們在討論的 web map 是不一樣的東西,請不要搞混了。例子如下:
const places = ["高雄", "台灣", "宇宙"]
const slogans = places.map(e=>e+"發大財") 
// slogans 變成 ["高雄發大財", "台灣發大財", "宇宙發大財"]

AJAX

還記得以前每次滑鼠點網頁總是要重新整理、載入一陣子才有畫面嗎?如果沒有這段記憶,我們的年紀可能差得有點多了。
在 1999 微軟發明 AJAX 之後,網頁瀏覽器具備了可以在不重新整理頁面也能取得所需資料的超能力。請看如下範例網頁:
https://www.maptiler.com/google-maps-coordinates-tile-bounds-projection/
在我們每次縮放的時候,其實瀏覽器都有按照寫好的 JS 指令要求去拿各個不同解析度的圖檔,在以前,每次縮放可都是要重新整理一次頁面呢。如果今天的網頁地圖是這樣,想必很多人用不下去吧。

JS 函式庫

前面提到的大多是任何瀏覽器都有支援的原生函數/語法。
軟體世界有個名言是不要重複造輪子。幾乎任何程式語言、任何你想得到的功能,只要你找對方向,幾乎都能找到網路上的朋友寫好的函式庫。而上提到的 module 語法就可以用來包裝/引用各種方便的 JS 套件。

例如原生的 document.selector 有點繁複的等語法在一套名為 D3.js 裡會變得比較簡潔一點,另外 D3 也可以用來幫我們繪製地圖以及相關圖表。

來用 D3 畫個地圖吧

範例:
http://bl.ocks.org/owlfox/198b5deaacf59a0495513c6dba239943

這裡我拿參考書籍裡的程式碼來做範例(不好意思我還在找合用的台灣地圖資料)。這裡我們需要引用外部的JS函式庫來協助開發,關於如何在 HTML 裡執行 JS,請參考這篇

這裡我們有用到外部的 json 檔案、D3 JS 我們下次再來介紹..

練習題

  • 寫一段簡單的程式碼來連點某個網頁的按鈕

下期預告

  • 網頁地圖用到的資料型態
    csv, svg/canvas, png, gif, shapefile, geojson, topojson
  • 經緯度、地球跟投影
  • 更多 D3.js 的範例還有介紹

參考資訊

Day3 JS intro

===

tags: ironman

Today we are going to show you things about JavaScript, its running environement: browser, how to play with dom, event, D3 and draw a small map as an ending.

By clicking the example page in the link below, we can see the number increases.

const reading = document.querySelector(`#count`)
let count = 0
document.addEventListener(`click`, (event)=>{
    count = count + 1
    reading.innerHTML = `Count: ${count}`
})

https://codepen.io/owlfox/pen/bGbyZjV
"object" is a common term/concept in programming. Here you can treat it as packing related information/code together for easy access.
As for the codes above

  • document is a global object available while JS running in browser. It is the actual data structure of the HTML after being parsed by the browser.
  • We executed the querySelector method in document object, ask it to search an element in html with id equals to could, and then return the result to the constant variable reading
  • Then we use the addEventListener method from document to allow the browser do the work while somene clicked the document. Here the work is add 1 to the count variable, and change the text of reading element

some history

JavaScript( hereinafter called JS)was crafted by Mr. Brendan Eich, who was working for Netscape at 1995. It was a language designed to be executed on their own browser at a time which IE, Chrome, Firefox were not exist.

This langualge enables the browser to interact with user inputs after opened the url, fetched html file and rendered the stuff in the window.

JS is adopted by the rest of the browsers. Then here comes European Computer Manufacturers Association (ECMA), organizing with different companies, make a JS specification, allows the same JS file to be able to be runned on different browsers and comes out the same results. There are different versions of the specm and we also call JavaScript as EcmaScript. Sometimes you might find a version of JS called ES2015/ES6. That's the most popular one at the moment. If you would like to know if a spec of JS or CSS is available on different browsers check the website named caniuse.

DOM

DOM, Document Object Model, a jargon you know the meaning of every words while have no idea what it is when they write together. Here I think it as the strickly structured format of how different vendors of browser store the parsed html file into a object for JS and CSS to access. W3C is the organization to draft and release the spec of DOM and many other stuff. The above is an example of manuplating DOM.

Chrome Developer tool

While we were developing our code/service, unexpected errors/behaviours happen from time to time. For web application, our browser could also be an helpful tool to find where went wrong. Right click on the page -> inspect element will pop a small window to display the source html code of the page, the CSS styles applied. While in the source tab, you can also add break points in your code to inspect the states of the program at a specific line of code. As for consle tab, you can write code there to see the results, error message, runtime states. Lastly the network tab shows you when and what browser requested/sent with this web application.

For the example code below you can just paste them into the console to see the results.

intro to some of the ES6 syntaxs

Below is the list of ES6 syntaxs we will use during the series:

  • const, assign once, won't change later
  • let ,for the rest of the const use let
  • var (older syntax, easy to make scope mistakes, avoid using it)
  • 箭頭函式(()=>()) shorter syntax for a function, good to use as argument formap, filter functions。
  • module packing/orgrnizing your code base with export/import syntax
  • classes a popular language feature supported since ES6 。
    Class is like a blueprint of building a house, which we can pack the related data/code together.
class Animal {
 constructor(name) {
     this.name = name
 }
 printName() {
     console.log(this.name)
 }
}

class Dog extends Animal {
  bark() {
  console.log(`${this.name}: Bow!`)
  }
}

let beddy = new Dog("beddy")
beddy.bark()
//beddy: Bow!
  • ... spread/Rest operator
    a syntax sugar ... to spread a array
let a = [1,2,3]
let b = [...a, 4] //[1,2,3,4]

or pack arguments of function into a array

function f(...args){
    return args.filter(e=>e===1)
}
f(1,2,3,4) //return [1]
let a, b = 1, 2
[a,b] = [b,a]
let a = {name:"beddy", age: -1}
let {name, age} = a 
  • Reference / Primitive types
    JS has 6 primitive types string、number、boolean、null、undefined、symbol, and many other objects。 while we were assigning value to a variable, primitive typed value will get copied while others are just a reference.
let a = 2
let b = a
b = 3
console.log(a,b) 
//2,3 a real copy

let c = [1]
let d = c
d.push(2) 
console.log(c,d) 
//[1,2] [1,2] just a reference, 
//you are playing the same object
  • map the map here is not a web map but a JS function to "map" every elements of an array. Example:
const places = ["高雄", "台灣", "宇宙"]
const slogans = places.map(e=>e+"發大財") 
// slogans 變成 ["高雄發大財", "台灣發大財", "宇宙發大財"]

AJAX

Do you have a memory of clicking a webpage and every time you clicked you have to wait the browser to reload the page, which is quite annoying? If not, dont talk to me!
Our browser comes with ability to fetch the data without reloading the pack since 1999, AJAX crafted by Microsoft. See the example below:
https://www.maptiler.com/google-maps-coordinates-tile-bounds-projection/
While we were pan/zooming the map, browser fetched the pictures of different resolution under the hood. It would be quite frustratingunusable if we have to reload the page every time we interact with the map.

JS library

Above are the objects, syntaxes supported out of the box, or say VanillaJS.
"Dont reinvent the wheel" is a famous quote from software sommunity. You can find nearly every feature/function you need from the internet written by someone else. The "module" tool above is to help us reuse the works done by the world.

Like the document.selector syntax abobe, you can use a library called D3.js to make them shorter and easier to read/maintain. D3 can also be used to draw graph, maps and many other things!

draw a map with D3

example:
http://bl.ocks.org/owlfox/198b5deaacf59a0495513c6dba239943

The above code is adopted from the book in the reference, I am still trying to find a good Taiwan geodat though.. For the information of how to import JS library/file, please have a look at this article

There are json files and many d3.js codes involved, we will continue our study tomorrow(?)

Exercise

  • Write a code to click an webpage like crazy automatically

next episode

  • data formats:
    csv, svg/canvas, png, gif, shapefile, geojson, topojson
    latitude, longitude, globe and projections
  • more D3 example, and intro

reference


上一篇
做一個簡單的地圖網頁(一) Build a simple web map part 1
下一篇
網頁地圖資料格式 web map data formats
系列文
我所知道的計算機 2019 What I know about computers6
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言